<?php 
	class User{
		private $uid;
		private $fields;
		public function __construct(){
			$this->uid = null;
			$this->fields = array('username'=>'',
									'password'=>'',
									'emailAddr'=>'',
									'isActive'=>false);
		}
		public function __get($field){
			if($field == 'userId'){
				return $this->uid;
			}else{
				return $this->$fields[$field];
			}
		}

		public function __set($field,$value){
			if(array_key_exists($field,$this->$fields)){
				$this->$fields[$field]=$value;
			}
		}

		public static function getById($userId){
			$user = new User();
			$query = sprintf('SELECT USERNAME,PASSWORD,EMAIL_ADDR,IS_ACTIVE '.
				'FROM %sUSER WHERE USER_ID =%d ',DB_TBL_PREFIX,$userId);
			$result = mysql_query($query,$GLOBALS['DB']);
			if(mysql_num_rows($result)){
				$row = mysql_fetch_assoc($result);
				$user-> username = $row['USERNAME'];
				$user-> password = $row['PASSWORD'];
				$user-> emailAddr = $row['EMAIL_ADDR'];
				$user-> isActive = $row['IS_ACTIVE'];
				$user-> uid = $userId;
			}
			mysql_free_result($result);
			return $user;
		}

		public static function getByUserName($username){
			$user = new User();
			$query = sprintf('SELECT USERNAME,PASSWORD,EMAIL_ADDR,IS_ACTIVE '.
				'FROM %sUSER WHERE USERNAME =%d',DB_TBL_PREFIX,mysql_real_escape_string($username,$GLOBALS['DB']));;
			$result = mysql_query($query,$GLOBALS['DB']);
			if(mysql_num_rows($result)){
				$row = mysql_fetch_assoc($result);
				$user-> username = $row['USERNAME'];
				$user-> password = $row['PASSWORD'];
				$user-> emailAddr = $row['EMAIL_ADDR'];
				$user-> isActive = $row['IS_ACTIVE'];
				$user-> uid = $row['USER_ID'];
			}
			mysql_free_result($result);
			return $user;
		}

		public static function save(){
			if($this->uid){
				$query = sprintf('UPDATE %sUser SET USERNAME = "%s",'.
					'PASSWORD="%s",EMAIL_ADDR="%s",IS_ACTIVE=%d '.
					'WHERE USER_ID = %d',DB_TBL_PREFIX,
					mysql_real_escape_string($this->username,$GLOBALS['DB']),
					mysql_real_escape_string($this->password,$GLOBALS['DB']),
					mysql_real_escape_string($this->emailAddr,$GLOBALS['DB']),
					$this->isActive,$this->userId
					);
				return mysql_query($query,$GLOBALS['DB']);
			}else{
				$query = sprintf('INSERT INTO %sUser(USERNAME,PASSWORD,'.
					'EMAIL_ADDR,IS_ACTIVE) VALUES("%s","%s","%s",%d)',
					DB_TBL_PREFIX,
					mysql_real_escape_string($this->username,$GLOBALS['DB']),
					mysql_real_escape_string($this->password,$GLOBALS['DB']),
					mysql_real_escape_string($this->emailAddr,$GLOBALS['DB']),
					$this->isActive);
				if(mysql_query($query,$GLOBALS['DB'])){
					$this->uid = mysql_insert_id($GLOBALS['DB']);
					return true;
				}else{
					return false;
				}
			}
		}
	}
?>